import 'dart:async';
import 'dart:io';

import 'package:number_spark_flutter/config/ns_global_config.dart';
import 'package:number_spark_flutter/network/ns_api.dart';
import 'package:number_spark_flutter/network/ns_network_config.dart';
import 'package:number_spark_flutter/routes/ns_app_pages.dart';
import 'package:number_spark_flutter/utils/ns_db_utils.dart';
import 'package:number_spark_flutter/utils/ns_log_report_utils.dart';
import 'package:number_spark_flutter/utils/ns_user_utils.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter_udid/flutter_udid.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import '../../network/ns_network_utils.dart';

class NSSplashLogic extends GetxController {
  StreamSubscription<ConnectivityResult>? _connectivitySubscription;
  final Connectivity _connectivity = Connectivity();
  bool isConnect = false;

  @override
  void onInit() {
    super.onInit();
    _connectivitySubscription = _connectivity.onConnectivityChanged.listen((ConnectivityResult result) {
      if (ConnectivityResult.none != result && !isConnect) {
        isConnect = true;
        onCheckLogin();
      }
    });
    Future.delayed(const Duration(milliseconds: 1000)).then((value) async {
      await getIosIDFA();
    });
  }

  Future<String> getIosIDFA() async {
    final TrackingStatus status = await AppTrackingTransparency.trackingAuthorizationStatus;
    if (status == TrackingStatus.notDetermined) {
      await Future.delayed(const Duration(milliseconds: 1000));
      final TrackingStatus status = await AppTrackingTransparency.requestTrackingAuthorization();
    }

    final uuid = await AppTrackingTransparency.getAdvertisingIdentifier();
    NSGlobalConfig.iosIDFA = uuid;
    return uuid;
  }

  @override
  void onClose() {
    _connectivitySubscription?.cancel();
    super.onClose();
  }

  onCheckLogin() async {
    String uuid = await FlutterUdid.udid;
    PackageInfo packageInfo = NSGlobalConfig.packageInfo;
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    NSNetWorkConfig config = NSNetWorkConfig(
        packageName: packageInfo.packageName,
        versionName: packageInfo.version,
        appVersionCode: int.parse(packageInfo.buildNumber),
        deviceId: uuid,
        platform: 'iOS',
        model: (await deviceInfo.iosInfo).model,
        successCode: '0',
        requestErrorTip: 'Network request failed',
        requestTimeoutTip: 'Network request timeout',
        noLoginCode: '401');
    NSNetWorkUtils.instance.initConfig(config);
    await onGetAppConfig();
    NSLogReportUtils.stat(page: NSLogPages.nsLaunch);
    await NSDBUtils().initDB();
    Future.delayed(const Duration(milliseconds: 500)).then((value) async {
      if (NSUserUtils.isLogin()) {
        Get.offNamed(NSRoutes.main);
        onCheckToken();
        onGetStrategy();
      } else {
        Get.offNamed(NSRoutes.login);
      }
    });
  }

  onGetAppConfig() async {
    Map<String, dynamic> params = {'ver': NSUserUtils.getAppConfig()['ver'] ?? 0};
    NSResponseData responseData = await NSApi.getAppConfig.get(params);
    if (responseData.isSuccess()) {
      if (responseData.data is Map) {
        NSUserUtils.setAppConfig(responseData.data);
      }
    }
  }

  onGetStrategy() async {
    NSResponseData responseData = await NSApi.getStrategy.get({});
    if (responseData.isSuccess()) {}
  }

  onCheckToken() async {
    Map<String, dynamic> params = {'token': NSNetWorkUtils.getAccessToken()};
    NSResponseData responseData = await NSApi.isValidToken.post(params);
    if (responseData.isSuccess()) {
    } else {
      NSNetWorkUtils.setAccessToken('');
      Get.offNamed(NSRoutes.login);
    }
  }
}
